<template>
  <view class="cc_video">
    <view v-if="loading" class="video-loading">
      <u-loading mode="flower" :size="60" :color="globPrimaryColor" v-if="loading"></u-loading>
    </view>
    <!-- 授权播放页面 -->
    <view class="authBox" v-if="isPlayAuth">{{ authmessage }}</view>
    <view v-if="!previewEnd" class="ccH5PlayerBox">
      <!-- video -->
      <video
        id="ccVideo"
        class="ccVideo"
        :src="videoSrc"
        :title="detailsInfo.title"
        :autoplay="autoplay"
        :controls="videoControls"
        :initial-time="initialTime"
        :duration="vDuration"
        @play="vPlay"
        @pause="vPause"
        @waiting="vWaiting"
        @error="vError"
        @progress="vProgress"
        @loadedmetadata="vLoadedmetadata"
        @ended="vEnd"
        :poster="videoPoster"
        @fullscreenchange="vFullScreen"
        @timeupdate="vTimeupdate"
      >
        <!-- 版权 -->
        <notice-bar
          v-if="isFullScreen && copyrightShow == 1"
          :width="noticeScreenWidth"
          :text="copyrightContent"
          :fontSize="12"
          :frequency="playerData.marquee.frequency"
          color="#ffffff"
          :defaultStyle="{
            top: '20rpx',
            left: '0px',
            background: 'rgba(0, 0, 0, 0.2)',
          }"
        ></notice-bar>
        <notice-bar
          v-if="!isFullScreen && copyrightShow == 1"
          :width="noticeWidth"
          :text="copyrightContent"
          :fontSize="12"
          :frequency="playerData.marquee.frequency"
          color="#ffffff"
          :defaultStyle="{
            top: '20rpx',
            left: '45px',
            background: 'rgba(0, 0, 0, 0.2)',
          }"
        ></notice-bar>

        <!-- 跑马灯 -->
        <notice-bar
          v-if="usingMarquee"
          width="100%"
          :text="marqueeText"
          :fontSize="playerData.marquee.font_size"
          :frequency="playerData.marquee.frequency"
          :color="marqueeColor"
        ></notice-bar>

        <!-- 音频背景图 -->
        <!-- #ifndef APP-PLUS -->
        <cover-view class="audio-bg" :style="{ display: isAudio ? 'block' : 'none' }">
          <cover-image :src="audioBg"></cover-image>
        </cover-view>
        <!-- #endif -->
        <!-- 自定义操作界面 -->
        <slider
          v-if="!videoControls"
          class="video-control-slider"
          :activeColor="globPrimaryColor"
          :value="vCurrentTime"
          :max="vDuration"
          backgroundColor="rgba(195,197,198,.5)"
          :block-size="16"
          @change="seeked"
          @changing="seeking"
        >
        </slider>
        <cover-view v-if="!videoControls" class="video-control-tool">
          <!-- 播放暂停按钮 -->
          <cover-image
            class="video-control-play"
            @tap="onVideoPlay"
            :src="!isPlaying ? '/static/images/play.png' : '/static/images/pause.png'"
          ></cover-image>
          <!-- 播放时间 -->
          <cover-view class="video-control-current">
            {{ currentTimeText }}
          </cover-view>
          <cover-view class="video-control-number">/</cover-view>
          <!-- 播放时间 -->
          <cover-view class="video-control-duration">
            {{ totalTimeText }}
          </cover-view>

          <!-- 全屏按钮 -->
          <cover-image
            class="video-control-fullscreen"
            @tap="fullScreen"
            src="@/pageCourse/static/images/fullscreen.png"
          ></cover-image>
        </cover-view>

        <!-- 清晰度按钮 -->
        <cover-view class="current-quality" @tap.stop="clickHdShow">{{ ccH5hdTxt }}</cover-view>

        <!-- 倍速按钮 -->
        <cover-view class="current-rate" @tap.stop="clickSpShow">{{ ccH5spTxt }}</cover-view>

        <!-- 清晰度列表 -->
        <cover-view
          class="quality-list"
          :style="{ display: hdShow ? 'block' : 'none' }"
          @tap.stop="clickHdShow"
        >
          <cover-view class="quality-list-wrap">
            <cover-view
              class="quality-item"
              :class="ccH5hdTxt == item.desp ? 'active' : ''"
              v-for="(item, index) in videoSrcList"
              :key="index"
            >
              <cover-view @tap.stop="changeQuality(item)">{{ item.desp }}</cover-view></cover-view
            >
          </cover-view>
        </cover-view>

        <!-- 倍速列表 -->
        <cover-view
          class="rate-list"
          :style="{ display: spShow ? 'block' : 'none' }"
          @tap.stop="clickSpShow"
        >
          <cover-view class="rate-list-wrap">
            <cover-view
              class="rate-item"
              :class="ccH5spTxt == item.txt ? 'active' : ''"
              hover-class="active"
              v-for="(item, index) in spList"
              :key="index"
              ><cover-view @tap.stop="changeSpeed(item)">{{ item.txt }}</cover-view></cover-view
            >
          </cover-view>
        </cover-view>
      </video>
    </view>
    <!-- 试看 -->
    <view v-if="previewEnd" class="video-audition">
      <view class="text">试看已结束</view>
      <view class="u-flex">
        <view class="item">
          <edu-button type="primary" size="mini" @click="onPreviewDurationPay(1)"
            >购买该课程</edu-button
          >
        </view>
        <edu-button
          type="primary"
          size="mini"
          @click="onPreviewDurationPay(2)"
          v-if="Number(getCurrentPlayItem.price) > 0"
          >购买该课时</edu-button
        >
      </view>
    </view>

    <!-- 防挂机-弹窗 -->
    <prevent-popup
      v-if="detailsInfo.onhook_type == 1"
      ref="refPreventPopupVerify"
      :datas="playerData.onhook"
      @click="onVerifySuccess"
    ></prevent-popup>

    <!-- 防挂机-弹题 -->
    <prevent-question
      v-else-if="detailsInfo.onhook_type == 2"
      ref="refPreventQuestionVerify"
      :course_id="detailsInfo.id"
      :course_type="detailsInfo.course_type"
      @click="onVerifySuccess"
    ></prevent-question>

    <!-- 防挂机-人脸 -->
    <edu-face
      v-else-if="detailsInfo.onhook_type == 3"
      ref="refFaceVerify"
      @confirm="onFaceVerifyConfirm"
    ></edu-face>
  </view>
</template>

<script>
let StatisClass = require('./statis.js') //初始数据
import { mapState, mapGetters } from 'vuex'
import { uploadFile } from '@/utils/uploadFile.js'
import preventQuestion from '../preventQuestion'
import preventPopup from '../preventPopup'
import noticeBar from '../notice-bar'
export default {
  props: {
    detailsInfo: {
      type: Object,
      default: () => {},
    },
    course_lock: {
      type: [String, Number],
      default: '',
    },
  },
  components: {
    preventQuestion,
    preventPopup,
    noticeBar,
  },
  data() {
    return {
      statis: null,
      ccVideo: null,
      videoSrcList: [], // 获取视频地址列表
      videoSrc: '', // 显示的视频地址
      videoPoster: '', // 视频封面
      videoControls: true, // controls
      isPlaying: false, // 是否正在播放
      vCurrentTime: 0, // video播放时间
      vDuration: 0, // video总时间
      initialTime: 0, // 指定视频初始播放位置
      ccH5spTxt: '常速',
      spShow: false, // 倍速显示隐藏
      hdShow: false, // 清晰度显示隐藏
      ccH5hdTxt: '', // 清晰度按钮信息
      authenable: -1, // 授权播放
      freetime: 0, // 授权播放时间
      authmessage: '', // 授权播放提示信息
      isPlayAuth: false, // 授权播放界面隐藏
      authCallback: null, // 授权播放回调
      authOpen: false,
      banDrag: false, // 是否禁止快进
      lastTime: 0, // 判断是否快进，禁止拖动使用
      lastTimeMax: 0,
      isAudio: false,
      audioBg: '',
      started: false,
      spList: [
        {
          num: '1.5',
          txt: '1.5倍',
        },
        {
          num: '1.25',
          txt: '1.25倍',
        },
        {
          num: '1',
          txt: '常速',
        },
        {
          num: '0.8',
          txt: '0.8倍',
        },
      ],
      freeTimeInterval: null,
      piTime: 0,
      initTime: 0,
      isWaiting: false,
      loaded: false,
      played: false,
      continue: false, // 播放完成后是否继续播放下一首，需定义@next事件
      autoplay: false, // 是否自动播放
      isFullScreen: false, // 是否处于全屏
      initialLoading: true, // 首次加载
      loading: true, //是否处于读取状态
      timer: null, // 计时器
      currentDuration: 0, // 记录学习时长
      previewEnd: false, // 试看状态
      previewDuration: 0, // 视频试看时长
      faceModalVisible: false, // 人脸验证弹出
      faceVerifyEnd: true, // 人脸验证结束
      faceVerifyNumber: 0, // 还需要验证次数
      faceIntervalTime: 0, //见时间间隔
      faceNextVerifyTime: 0, // 下一次验证时间
      faceSceneType: 2, // 场景
      faceSceneId: 0, // 验证id
      faceShootStatus: false, // 续播状态

      usingMarquee: false, // 是否显示跑马灯
      marqueeText: '',

      playerData: {}, // 播放数据
      copyrightContent: '', // 版权内容
      copyrightShow: 0, // 是否显示版权信息
      noticeWidth: '',
      noticeScreenWidth: '',
    }
  },
  computed: {
    ...mapGetters({
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
      hasLogin: 'user/getHasLogin',
      globNavbarRightButtonWidth: 'projectSetting/globNavbarRightButtonWidth',
    }),
    ...mapState({
      getCurrentPlayItem: (state) => state.course.currentPlayItem,
    }),
    custom_id() {
      return this.getCurrentPlayItem.id
    },
    currentTimeText() {
      return this.timeFormat(this.vCurrentTime)
    },
    totalTimeText() {
      return this.timeFormat(this.vDuration)
    },
    marqueeColor() {
      const marqueeData = this.playerData.marquee
      if (!this.$u.test.empty(marqueeData)) {
        return this.$edu.test.hexToRgba(marqueeData.font_color, marqueeData.font_opacity)
      }
      return ''
    },
  },
  mounted() {
    // 暂停播放
    uni.$on('sectionPlayerPause', () => {
      if (this.ccVideo) {
        this.ccVideo.pause()
      }
    })
  },
  methods: {
    /**
     * 播放下一个
     */
    changeNext() {
      this.clearIntervals()
      this.started = false
      this.$store.commit('course/setCurrentPlayItem', {
        ...this.getCurrentPlayItem,
        ...this.playerData.next_position,
      })
      this.autoplay = true
      if (this.ccVideo) {
        this.ccVideo.pause()
      }
      this.$emit('next')
    },
    /**
     * 播放初始化
     */
    init: function (vid, siteid) {
      this.copyrightShow = 0
      this.usingMarquee = false
      this.loading = true
      this.loaded = false
      this.played = false
      this.initTime = new Date().getTime()
      this.ccVideo = uni.createVideoContext('ccVideo', this)
      let res = uni.getSystemInfoSync()
      let uaModel = 'iPhone'
      if (res && res.system) {
        let lowerCaseModel = res.system.toLowerCase()

        if (lowerCaseModel.startsWith('android')) {
          uaModel = 'Android'
        }
      } else {
        uaModel = 'Android'
      }
      this.started = true
      this.getData(vid, siteid, uaModel, this.showPlayer)
    },
    /***
     * 视频暂停事件回调
     */
    vPause: function () {
      this.isPlaying = false
      this.isWaiting = false
      if (this.vCurrentTime != this.vDuration) {
        //暂停播放播放日志
        this.statis.flareTogglePlay(1)
        clearInterval(this.timer)
        this.handleAddLearning()
      }
    },
    /***
     * 视频播放事件回调
     */
    vPlay: function () {
      if (!this.started) {
        this.ccVideo.pause()
        return
      }
      this.isPlaying = true
      if (!this.played) {
        this.played = true //播放心跳日志
        this.statis.flareHeartJump() //第一次播放flare日志
        this.statis.flareFirstPlay(this.readyTime) //开始播放flare日志
      }
      this.statis.flareTogglePlay(2)

      this.timer = setInterval(() => {
        this.currentDuration++
        if (this.currentDuration % 10 == 0) {
          this.handleAddLearning()
        }
      }, 1000)

      this.onVerifyTimeupdate()
    },
    /***
     * 视频加载中事件回调
     */
    vWaiting: function (e) {
      if (!this.loaded) {
        return
      }
      if (this.vCurrentTime - this.lastTime < 2 && this.vCurrentTime >= this.lastTime) {
        //正常播卡才发送日志，排除拖拽行为的播卡
        this.isWaiting = true
        this.statis.flareVideoWaiting(
          parseInt(this.vCurrentTime * 1000),
          parseInt(this.vCurrentTime * 1000)
        )
      }
    },
    /***
     * 视频播放出错事件回调
     */
    vError: function (e) {
      //停止播放心跳
      this.statis && this.statis.flareHeartStop()
      this.statis && this.statis.flareVideoLoadFail(this.played)
    },
    /***
     * 视频播放结束事件回调
     */
    vEnd: function (e) {
      //设置播放时间
      this.vCurrentTime = Math.floor(this.vDuration)
      this.lastTime = this.vDuration
      this.lastTimeMax = this.vDuration //播放结束flare日志
      this.statis.flarePlayEnded() //停止播放心跳
      this.statis && this.statis.flareHeartStop()
      clearInterval(this.timer)
      this.handleAddLearning()
      // 顺序模式
      if (this.course_lock == 1) return
      this.handleContinuousPaly()
    },
    /***
     * 加载进度变化时事件回调
     */
    vProgress: function (e) {
      if (!this.loaded) {
        return
      }
      if (this.isWaiting) {
        this.isWaiting = false
        let currentTime = this.vCurrentTime
        setTimeout(() => {
          if (this.vCurrentTime == currentTime) {
            this.isWaiting = true
            return
          } //缓冲结束flare日志
          this.statis.flareVideoWaitingOver(
            parseInt(this.vCurrentTime * 1000),
            parseInt(this.vCurrentTime * 1000),
            0
          )
        }, 500)
      }
    },
    /***
     * 视频元数据加载后事件回调
     */
    vLoadedmetadata: function () {
      this.loaded = true
      this.isWaiting = false
      this.vDuration = this.getCurrentPlayItem.section_data.duration || 0
      this.readyTime = new Date().getTime() - this.initTime //播放准备flare日志
      this.statis.flareReadyStage(this.piTime, this.readyTime)

      // #ifndef APP-PLUS
      const marqueeData = this.playerData.marquee
      if (!this.$u.test.empty(marqueeData)) {
        // 版权声明
        this.copyrightContent = marqueeData.copyright_content
        let screenWidth = this.$u.sys().screenWidth
        this.noticeWidth = screenWidth - uni.upx2px(276) - this.globNavbarRightButtonWidth + 'px'
        this.noticeScreenWidth = this.$u.sys().screenHeight + 'px'
        setTimeout(() => {
          this.copyrightShow = marqueeData.copyright
        }, 1000)

        // 跑马灯
        const dataType = this.getCurrentPlayItem.section_data.data_type
        if (dataType == 1 && this.hasLogin) {
          let name = ''
          let phone = ''
          if (marqueeData.username) name = this.userInfo.nick_name
          if (marqueeData.phone) phone = this.userInfo.phone
          this.marqueeText = name + phone
          setTimeout(() => {
            this.usingMarquee = true
          }, 1000)
        }
      }
      // #endif

      setTimeout(() => {
        // 首次执行
        if (this.initialLoading) {
          this.handleAuditionTime()
          this.handleInitialTime()
          this.handleVerifyInit()
          this.initialLoading = false
        }

        this.loading = false
      }, 600)
    },
    /***
     * 监听播放器的播放进度
     */
    vTimeupdate: function (e) {
      let currentTime = e.detail.currentTime || 0
      let durationTime = e.detail.duration || 0
      if (durationTime - currentTime < 0.5) {
        currentTime = durationTime
      }
      this.vCurrentTime = Math.floor(currentTime)
      this.vDuration = durationTime

      if (this.banDrag && e.detail.currentTime - this.lastTimeMax > 2) {
        this.ccVideo.seek(this.lastTime)
        return
      }

      this.lastTime = e.detail.currentTime

      if (this.lastTime >= this.lastTimeMax) {
        this.lastTimeMax = this.lastTime
      }

      this.onPreviewDurationEnd() // 试看
      this.onVerifyTimeupdate() // 人脸
    },
    /***
     * 监听全屏后显示系统进度条
     */
    vFullScreen: function (e) {
      this.started = true
      if (e.detail.fullScreen) {
        this.isFullScreen = true
      } else {
        this.isFullScreen = false
      }
    },
    /***
     * 播放器点击播放
     */
    onVideoPlay: function () {
      this.started = true
      if (this.authenable == 0 && !this.authOpen) {
        this.playAuth()
        this.authOpen = true
      }
      if (!this.isPlaying) {
        this.ccVideo.play()
        this.isPlaying = true
      } else {
        this.ccVideo.pause()
        this.isPlaying = false
      }
      // 试看播放结束
      if (this.previewEnd) {
        this.ccVideo.seek(0)
        this.previewEnd = false
      }
    },
    /***
     * 点击切换倍速
     */
    changeSpeed: function (item) {
      if (item.txt == this.ccH5spTxt) {
        this.spShow = false
        return
      }

      let oldSp = 1
      let spList = this.spList

      for (let sp of spList) {
        if (sp.txt == this.ccH5spTxt) {
          oldSp = sp.num
          break
        }
      }
      let spNum = item.num
      let spTxt = item.txt
      this.ccH5spTxt = spTxt
      this.spShow = false
      this.ccVideo.playbackRate(Number(spNum)) //切换倍速flare日志
      this.statis.flareChangeSpeed(oldSp, spNum)
    },
    /***
     * 点击切换清晰度
     */
    changeQuality: function (e) {
      if (e.desp == this.ccH5hdTxt) {
        this.hdShow = false
        return
      }
      let hdTxt = e.desp
      let vTime = this.vCurrentTime
      let oldUrl = this.videoSrc
      let hdUrl = ''

      if (!!this.custom_id) {
        hdUrl = e.playurl + '&custom_id=' + this.custom_id
      } else {
        hdUrl = e.playurl
      }
      this.ccH5spTxt = '常速'
      this.ccH5hdTxt = hdTxt
      this.videoSrc = hdUrl
      this.hdShow = false
      this.ccVideo.playbackRate(1)
      this.isPlaying = false
      this.ccVideo.play()
      this.gotoSeek(vTime) //切换清晰度flare统计
      this.initialLoading = false
      this.statis.flareSwitchQuality(oldUrl, hdUrl)
    },
    /**
     * 跳转到某个时间点播放
     */
    gotoSeek: function (duration) {
      this.started = true
      if (this.lastTimeMax < duration) {
        this.lastTimeMax = duration
      }
      let that = this
      setTimeout(function () {
        that.ccVideo.play()
        if (!that.isPlaying) {
          that.gotoSeek(duration)
          return
        }
        that.ccVideo.seek(duration)
      }, 200)
    },
    /***
     * 点击显示隐藏倍速列表
     */
    clickSpShow: function () {
      if (this.spShow) {
        this.spShow = false
        this.hdShow = false
      } else {
        this.spShow = true
        this.hdShow = false
      }
    },
    /***
     * 点击显示隐藏清晰度列表
     */
    clickHdShow: function () {
      if (this.hdShow) {
        this.spShow = false
        this.hdShow = false
      } else {
        this.spShow = false
        this.hdShow = true
      }
    },
    /***
     * 时间转成00:00格式
     */
    timeFormat: function (time) {
      time = time < 0 ? 0 : time
      var t = parseInt(time)
      var h
      var i
      var s
      h = Math.floor(t / 3600)
      if (h) {
        h = h + ':'
      } else {
        h = ''
      }
      if (h) {
        i = Math.floor((t % 3600) / 60)
      } else {
        i = Math.floor(t / 60)
      }
      s = Math.floor(t % 60)
      if (i > 9) {
        i = i
      } else {
        i = '0' + i
      }
      if (s > 9) {
        s = s
      } else {
        s = '0' + s
      }
      return h + i + ':' + s
    },
    /***
     * 全屏播放
     */
    fullScreen: function () {
      this.ccVideo.requestFullScreen()
    },
    /***
     * 正在拖动进度条
     */
    seeking(e) {
      this.ccVideo.pause()
      this.vCurrentTime = Math.floor(e.detail.value)
    },
    /***
     * 拖动进度条结束
     */
    seeked(e) {
      this.ccVideo.seek(Math.floor(e.detail.value))
      setTimeout(() => {
        this.ccVideo.play()
      }, 300)
      this.statis.flareSeeked(this.lastTime, e.detail.value)
    },
    /***
     * 播放授权
     */
    playAuth: function () {
      let that = this

      if (this.authmessage == '') {
        this.authmessage = '不允许观看或试看时间用尽'
      }

      if (this.freetime == 0) {
        this.isPlayAuth = true
        if (that.authCallback != '') {
          if (typeof that.authCallback == 'function') {
            that.authCallback()
          }
        }
        return
      }

      let freeT = setInterval(function () {
        if (that.vCurrentTime < that.freetime) {
          clearInterval(freeT)
          return
        }

        clearTimeout(freeT)
        that.isPlayAuth = true
        that.authOpen = false

        if (that.authCallback != '') {
          if (typeof that.authCallback == 'function') {
            that.authCallback()
          }
        }
      }, 500)
      this.freeTimeInterval = freeT
    },

    /***
     * 获取视频数据后的回调
     */
    showPlayer: function (data) {
      data = data.substring(data.indexOf('(') + 1, data.length - 1)
      let dataObj = JSON.parse(data) //初始化统计

      this.initStatis(dataObj) // custom_id

      let custom_id = this.custom_id
      let vSrc = '' // 避免获取视频信息出错时报错

      if (dataObj.copies.length === 0) {
        this.readyTime = new Date().getTime() - this.initTime
        this.statis.flareReadyStage(this.piTime, this.readyTime)
        return
      }

      if (!!this.custom_id) {
        vSrc = dataObj.copies[0].playurl + '&custom_id=' + custom_id
      } else {
        vSrc = dataObj.copies[0].playurl
      }

      let isAudio = false
      let videoPoster = dataObj.img
      let audioBg = ''

      if (dataObj.copies[0].mediatype != 1) {
        isAudio = true
        videoPoster = ''
        audioBg = dataObj.img
      }
      this.lastTimeMax = 0
      this.videoSrcList = dataObj.copies
      this.videoSrc = vSrc
      this.videoPoster = videoPoster
      this.ccH5hdTxt = dataObj.copies[0].desp
      this.isAudio = isAudio
      // this.audioBg = audioBg
      this.audioBg = this.detailsInfo.cover_url

      if (dataObj.authenable == 0) {
        this.authenable = dataObj.authenable
        this.authmessage = dataObj.authmessage
        this.authCallback = dataObj.callback
        this.freetime = dataObj.freetime
      }

      // #ifdef APP-PLUS
      this.vLoadedmetadata()
      // #endif
    },
    /***
     * 初始化统计
     */
    initStatis: function (dataObj) {
      let that = this //提供给统计使用的参数

      let params = {
        vid: that.vid,
        siteid: that.siteid,
        custom_id: that.custom_id,
      } //提供给统计使用的api

      let playerApi = {
        getCurrentTime: function () {
          return that.vCurrentTime
        },
        getDuration: function () {
          return that.vDuration
        },
        getVideoSrc: function () {
          return that.videoSrc
        },
      }
      that.statis = StatisClass.createStatis(params, dataObj, playerApi)
    },
    /***
     * 请求接口
     */
    getData: function (vid, siteid, uaModel, callback) {
      var that = this
      var startTime = new Date().getTime()
      uni.request({
        url: 'https://p.bokecc.com/servlet/getvideofile',
        data: {
          vid: vid,
          siteid: siteid,
          hlssupport: 1,
          useragent: uaModel,
          vc: '',
        },
        header: {
          'Content-Type': 'applciation/json',
        },
        method: 'GET',
        success: function (res) {
          that.piTime = new Date().getTime() - startTime
          callback(res.data)
        },
        fail: function (err) {},
      })
    },
    /***
     * 清楚定时任务
     */
    clearIntervals: function () {
      this.statis && this.statis.flareHeartStop()
      clearInterval(this.freeTimeInterval)
    },
    // 获取播放地址
    getPlayerFile(palyData) {
      this.reset()
      this.playerData = palyData
      this.continue =
        !this.$u.test.empty(palyData.next_position) &&
        !this.$u.test.empty(palyData.next_position.position)

      if (this.detailsInfo.onhook_type == 3) {
        this.faceSceneId = this.getCurrentPlayItem.id
      }
      this.$edu.api
        .getCourseSectionVideo(
          this.getCurrentPlayItem.course_id,
          this.getCurrentPlayItem.id,
          this.getCurrentPlayItem.section_data.stock
        )
        .then((res) => {
          const { data } = res
          this.init(data.videoid, data.userid) // 播放初始化
        })
    },
    reset() {
      this.loading = true
      this.previewEnd = false
      this.vCurrentTime = 0
      this.vDuration = 0
      this.initialTime = 0
      this.initialLoading = true
      this.isPlaying = false
      this.usingMarquee = false
      this.copyrightShow = 0
    },
    // 计算试听时长
    handleAuditionTime() {
      this.previewEnd = false
      let buy = this.getCurrentPlayItem.is_buy
      if (this.$edu.test.isDef(buy) && buy == 0) {
        let audition = this.getCurrentPlayItem.audition || 0
        this.previewDuration = Math.round(this.vDuration * (audition / 100))
      }
    },
    // 处理试看结束
    onPreviewDurationEnd() {
      if (
        this.previewDuration > 0 &&
        this.previewDuration < this.vDuration &&
        this.vCurrentTime > this.previewDuration
      ) {
        this.ccVideo.seek(this.previewDuration)
        this.ccVideo.pause()
        if (this.isFullScreen) {
          this.ccVideo.exitFullScreen()
        }
        this.previewEnd = true
      }
    },
    // 试看购买
    onPreviewDurationPay(type) {
      this.$edu.judgeLogin(() => {
        if (type == 1) {
          this.$u.route({
            type: 'redirectTo',
            url: '/pageCourse/cart/course',
            params: {
              id: this.getCurrentPlayItem.course_id,
            },
          })
        } else {
          this.$u.route({
            type: 'redirectTo',
            url: '/pageCourse/cart/section',
            params: {
              id: this.getCurrentPlayItem.id,
            },
          })
        }
      })
    },
    // 断点续播
    handleInitialTime() {
      let buy = this.getCurrentPlayItem.is_buy || 0
      let time = this.getCurrentPlayItem.section_rate.current_time || 0
      if (this.$edu.test.isDef(buy) && buy == 0) return
      if (this.vDuration > 0 && time > this.vDuration - 5) {
        this.vCurrentTime = 0
        this.initialTime = 0
        this.ccVideo.seek(0)
      } else {
        this.vCurrentTime = time
        setTimeout(() => {
          this.initialTime = time
          this.ccVideo.seek(parseInt(time))
        }, 1000)
      }
    },
    /* 人脸 START */
    handleVerifyInit() {
      // 课时是否购买
      let buy = this.getCurrentPlayItem.is_buy
      if (this.$edu.test.isDef(buy) && this.getCurrentPlayItem.is_buy == 0) return

      // 是否是视频
      let type = this.getCurrentPlayItem.section_data.data_type
      if (this.$edu.test.isDef(type) && type != 1) return

      // 是否开启验证
      if (this.detailsInfo.onhook_type == 0) return

      this.timer = null
      this.faceSceneType = 2
      this.faceShootStatus = false
      this.faceVerifyEnd = false
      this.faceNextVerifyTime = 0
      if (this.detailsInfo.onhook_type == 1) {
        const onhookData = this.playerData.onhook
        this.faceVerifyNumber = onhookData.alert_max_number // 验证次数
        this.faceIntervalTime = onhookData.alert_time_interval * 60 // 时间间隔
      } else if (this.detailsInfo.onhook_type == 2) {
        const examData = this.playerData.onhook_exam
        this.faceVerifyNumber = examData.answer_max_number // 验证次数
        this.faceIntervalTime = examData.answer_time_interval * 60 // 时间间隔
      } else if (this.detailsInfo.onhook_type == 3) {
        const faceData = this.playerData.face_data
        this.faceVerifyNumber = faceData.need_verify_number // 验证次数
        this.faceIntervalTime = faceData.verify_timespan * 60 // 时间间隔
      }

      this.nextVerifyTime()
    },
    // 计算下一次验证时间
    nextVerifyTime() {
      if (this.faceVerifyNumber > 0) {
        let time = this.currentDuration + this.faceIntervalTime
        this.faceNextVerifyTime = time
      } else {
        this.faceVerifyEnd = true
      }
    },
    // 播放时弹出人脸
    onVerifyTimeupdate() {
      // #ifndef APP
      if (
        !this.faceVerifyEnd &&
        this.faceNextVerifyTime > 0 &&
        this.faceNextVerifyTime <= this.currentDuration
      ) {
        uni.$u.debounce(
          () => {
            if (this.isFullScreen) {
              this.ccVideo.exitFullScreen()
            }
            if (this.detailsInfo.onhook_type == 1) {
              this.$refs.refPreventPopupVerify.onOpen()
            } else if (this.detailsInfo.onhook_type == 2) {
              this.$refs.refPreventQuestionVerify.onOpen()
            } else if (this.detailsInfo.onhook_type == 3) {
              this.handleModalConfirm()
            }
            this.ccVideo.pause()
          },
          1000,
          true
        )
      }
      // #endif
    },
    // 去验证人脸
    handleModalConfirm() {
      this.$refs.refFaceVerify.onFaceMessage()
    },
    // 人脸验证成功
    onVerifySuccess() {
      // 续播
      if (this.faceShootStatus) {
        this.changeNext()
      } else {
        this.faceVerifyNumber-- // 还需要验证次数
        this.nextVerifyTime()
        setTimeout(() => {
          this.onVideoPlay()
        }, 50)
      }
    },
    // 提交人脸验证
    onFaceVerifyConfirm(file) {
      uploadFile('/user/tencent/face/person/verify', file, {
        scene_key: 'course_section',
        scene_id: this.faceSceneId,
        scene_type: this.faceSceneType,
      })
        .then((res) => {
          this.$u.toast(res.msg)
          this.$refs.refFaceVerify.onClose()
          this.onVerifySuccess()
        })
        .catch((err) => {
          this.$u.toast(err.msg)
          this.$refs.refFaceVerify.resetPhoto()
        })
    },
    // 处理连续播放
    handleContinuousPaly() {
      if (this.continue) {
        if (this.isFullScreen) {
          this.ccVideo.exitFullScreen()
        }
        if (this.detailsInfo.onhook_type == 3) {
          this.handleModalConfirm()
          this.faceSceneType = 1
          this.faceSceneId = this.playerData.next_position.id
          this.faceShootStatus = true
        } else {
          this.changeNext()
        }
      }
    },
    // 添加学习记录
    handleAddLearning() {
      const item = this.getCurrentPlayItem
      if (this.$edu.test.isDef(item.is_buy) && item.is_buy == 0) return
      this.$edu.api.createCourseRecord({
        course_id: item.course_id,
        section_id: item.id,
        current_time: this.vCurrentTime,
      })
    },
    // 获取节点信息
    getElQuery(className) {
      return new Promise((resolve) => {
        let queryInfo = ''
        queryInfo = uni.createSelectorQuery().in(this)
        queryInfo.select(className).boundingClientRect()
        queryInfo.exec((data) => {
          resolve(data)
        })
      })
    },
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
}
</script>
<style lang="scss" scoped>
.cc_video {
  position: relative;
  width: 100%;
  height: 415rpx;
  background-color: #000000;

  .video-loading {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    z-index: 102;
    background-color: #000000;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .video-audition {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    z-index: 101;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 1);
    padding-top: 50px;
    .item {
      margin-right: 30rpx;
    }
    .text {
      font-size: 32rpx;
      font-weight: 400;
      color: #ebeef5;
      line-height: 45rpx;
      margin-bottom: 25rpx;
    }
  }

  .authBox {
    background: #000000;
    color: #ffffff;
    text-align: center;
    line-height: 200px;
  }

  .video-control-slider {
    margin: 0;
    position: absolute;
    bottom: 32px;
    left: 0;
    right: 0;
    z-index: 10;
    .uni-slider-handle {
      z-index: 10;
    }
  }

  .ccH5PlayerBox {
    position: relative;
    width: 100%;
    height: 100%;
    ::v-deep .audio-bg {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 9;
    }
    ::v-deep .video-control-tool {
      display: flex;
      align-items: center;
      padding: 0 10px;
      height: 40px;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 9;
      background: rgba(75, 75, 75, 0.15);
      box-sizing: border-box;
      overflow: visible;
      .video-control-current {
        width: 40px;
        font-size: 12px;
        color: #ffffff;
        margin-left: 6px;
        line-height: 32px;
        text-align: center;
      }

      .video-control-duration {
        width: 40px;
        font-size: 12px;
        color: #ffffff;
        line-height: 32px;
        text-align: center;
      }

      .video-control-number {
        font-size: 12px;
        color: #ffffff;
        line-height: 32px;
      }

      .video-control-play {
        width: 20px;
        height: 20px;
      }

      .video-control-fullscreen {
        width: 20px;
        height: 20px;
        margin-left: auto;
      }
    }

    .current-rate {
      position: absolute;
      right: 10px;
      top: 120px;
      z-index: 100;
      width: 48px;
      height: 24px;
      color: rgba(255, 255, 255, 0.7);
      font-size: 13px;
      line-height: 24px;
      text-align: center;
      border-radius: 2px;
      border: 1px solid rgba(255, 255, 255, 0.7);
    }

    .rate-list {
      background-color: rgba(0, 0, 0, 0.6);
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 102;
      .rate-list-wrap {
        position: absolute;
        left: 0;
        bottom: 50px;
        display: flex;
        align-items: flex-end;
      }
      .rate-item {
        width: 55px;
        height: 26px;
        color: #ffffff;
        text-align: center;
        font-size: 13px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        background-color: rgba(0, 0, 0, 0.3);
      }
      .active {
        color: #ff920a;
      }
    }

    .current-quality {
      position: absolute;
      right: 10px;
      top: 85px;
      z-index: 100;
      width: 48px;
      height: 24px;
      color: rgba(255, 255, 255, 0.7);
      font-size: 13px;
      line-height: 24px;
      text-align: center;
      border-radius: 2px;
      border: 1px solid rgba(255, 255, 255, 0.7);
    }

    .quality-list {
      background-color: rgba(0, 0, 0, 0.6);
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      z-index: 102;
      .quality-list-wrap {
        position: absolute;
        left: 0;
        bottom: 50px;
        display: flex;
        align-items: flex-end;
      }
      .quality-item {
        width: 55px;
        height: 26px;
        color: #ffffff;
        font-size: 13px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        background-color: rgba(0, 0, 0, 0.3);
      }
      .active {
        color: #ff920a;
      }
    }

    .ccVideo {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: #000000;
      display: block;
      z-index: 8;
    }
  }
}
</style>
